import os
import yaml


current_dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


class WebServerConfig:
    def __init__(self, url):
        self.url = url

    def __str__(self):
        return "url: {}".format(self.url)


class DataBaseConfig:
    def __init__(self, host, port, user, password, database):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database

    def __str__(self):
        return "host:{}, port:{}, user:{}, password:{}, database:{}"\
            .format(self.host, self.port, self.user, self.password, self.database)


class MongodbConfig:
    def __init__(self, host, port, database):
        self.host = host
        self.port = port
        self.database = database


class ConcurrencyConfig:
    def __init__(self, multi_process_number, single_process_loop_count, bucket_rate, bucket_capacity):
        self.multi_process_number = multi_process_number
        self.loop_count = single_process_loop_count
        self.bucket_rate = bucket_rate
        self.bucket_capacity = bucket_capacity

    def __str__(self):
        return "multi_process_number:{}, loop_count:{}, bucket_rate:{}, bucket_capacity:{}"\
            .format(self.multi_process_number, self.loop_count, self.bucket_rate, self.bucket_capacity)


class GlobalConfig:
    def __init__(self, config_file_name):
        self.__global_config = self.__get_global_config(config_file_name)
        if self.__global_config is None:
            raise Exception('get config file error')
        self.web_server = WebServerConfig(**self.__global_config['web_server'])
        self.database = DataBaseConfig(**self.__global_config['sql_database'])
        self.mongodb = MongodbConfig(**self.__global_config['mongo_database'])
        self.concurrency = ConcurrencyConfig(**self.__global_config['concurrency_constants'])

    @staticmethod
    def __get_global_config(self, config_file_name):
        config_file_path = os.path.join(current_dir_path, config_file_name)
        if not os.path.exists(config_file_path):
            return None
        with open(config_file_path, 'r', encoding='utf=-8') as f:
            cfg = yaml.load(f.read())
            return cfg
